﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using NDatabase;

namespace MediaRecommender.Model
{
    public class DbGateWay
    {
        private const string _dbFileName = "ndb.db";

        private static readonly DbGateWay _instance = new DbGateWay();

        public static DbGateWay Instance
        {
            get
            {
                return _instance;
            }
        }

        public void StoreList<T>(List<T> itemList) where T : class
        {
            using (var odb = OdbFactory.Open(_dbFileName))
            {
                foreach (T item in itemList)
                {
                    var q = odb.QueryAndExecute<T>().Where(x => x.Equals(item));
                    int count = q.Count(x => true);
                    if (count == 0) odb.Store<T>(item);
                }
            }
        }

        public void Store<T>(T item) where T : class
        {
            using (var odb = OdbFactory.Open(_dbFileName))
            {
                var q = odb.QueryAndExecute<T>().Where(x => x.Equals(item));
                int count = q.Count(x => true);
                if (count == 0) odb.Store<T>(item);
            }
        }

        public void Retrieve<T>(out List<T> returnItem, Expression<Func<T, bool>> predicate)
        {
            using (var odb = OdbFactory.Open(_dbFileName))
            {
                var q = odb.AsQueryable<T>().Where(predicate);
                returnItem = q.ToList<T>();
            }
        }

        public void Delete<T>(T item) where T : class
        {
            using (var odb = OdbFactory.Open(_dbFileName))
            {
                odb.Delete(item);
            }
        }
    }
}